<?php


namespace App\Services;

use App\Models\Question;
use App\Utils\Code;
use App\Utils\Tools;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Fukuball\Jieba\Jieba;
use Fukuball\Jieba\Finalseg;

class QuestionService extends BaseService
{
    /**
     * 创建数据
     * @param array $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function store(array $params) {
        if (!$this->checkParams($params)){
            throw new \Exception('请求参数验证不通过', Code::PARAMETER_ERROR);
        }
        return DB::transaction(function () use ($params){
            $model = new Question();
            if (isset($params['field_1']) && $params['field_1']) {
                $model->field_1 = $params['field_1'];
            }
            if (isset($params['field_2']) && $params['field_2']) {
                $model->field_2 = $params['field_2'];
            }
            if (isset($params['field_3']) && $params['field_3']) {
                $model->field_3 = $params['field_3'];
            }
            if (isset($params['field_4']) && $params['field_4']) {
                $model->field_4 = $params['field_4'];
            }
            if (isset($params['field_5']) && $params['field_5']) {
                $model->field_5 = $params['field_5'];
            }
            if (isset($params['field_6']) && $params['field_6']) {
                $model->field_6 = $params['field_6'];
            }
            if (isset($params['field_7']) && $params['field_7']) {
                $model->field_7 = $params['field_7'];
            }
            if (isset($params['field_8']) && $params['field_8']) {
                $model->field_8 = $params['field_8'];
            }
            if (isset($params['field_9']) && $params['field_9']) {
                $model->field_9 = $params['field_9'];
            }
            if (isset($params['field_10']) && $params['field_10']) {
                $model->field_10 = $params['field_10'];
            }
            $model->save();
            if (isset($params['qtags']) && is_array($params['qtags'])){
                $model->qtags()->sync($params['qtags']);
            }
            return true;
        });
    }

    /**
     * 数据信息
     * @param $id
     * @param bool $simple
     * @param bool $abnormal
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function show($id, $abnormal = true) {
        $model = Question::where('id', $id)->with(['qtags'])->first();
        if (!$model && $abnormal){
            throw new \Exception('不存在的ID', Code::EMPTY_DATA);
        }
        return $model;
    }

    /**
     * 更新数据
     * @param $id
     * @param array $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * @throws \Exception
     */
    public function update($id, array $params) {
        if (!$this->checkParams($params, true)){
            throw new \Exception('请求参数验证不通过', Code::PARAMETER_ERROR);
        }
        return DB::transaction(function () use ($id, $params){
            $model = $this->show($id);
            if (key_exists('field_1', $params)) {
                $model->field_1 = $params['field_1'];
            }
            if (key_exists('field_2', $params)) {
                $model->field_2 = $params['field_2'];
            }
            if (key_exists('field_3', $params)) {
                $model->field_3 = $params['field_3'];
            }
            if (key_exists('field_4', $params)) {
                $model->field_4 = $params['field_4'];
            }
            if (key_exists('field_5', $params)) {
                $model->field_5 = $params['field_5'];
            }
            if (key_exists('field_6', $params)) {
                $model->field_6 = $params['field_6'];
            }
            if (key_exists('field_7', $params)) {
                $model->field_7 = $params['field_7'];
            }
            if (key_exists('field_8', $params)) {
                $model->field_8 = $params['field_8'];
            }
            if (key_exists('field_9', $params)) {
                $model->field_9 = $params['field_9'];
            }
            if (key_exists('field_10', $params)) {
                $model->field_10 = $params['field_10'];
            }
            if (isset($params['qtags'])){
                if (is_array($params['qtags']) && $params['qtags']) {
                    $model->qtags()->detach();
                    $model->qtags()->sync($params['qtags']);
                } else {
                    $model->qtags()->detach();
                }
            }
            $model->save();
            return $this->show($id);
        });
    }

    /**
     * 删除数据
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public function destroy(array $ids = []) {
        if (!$this::$admin) {
            throw new \Exception('你没有权限进行删除', Code::LACK_OF_CONDITIONS);
        }
        return DB::transaction(function () use ($ids) {
            return Question::whereIn('id', $ids)->delete();
        });
    }

    /**
     * 数据分页
     * @param array $params
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function lists(array $params = []) {
        $model = Question::with(['qtags']);
        if (isset($params['field_1']) && $params['field_1']) {
            $select = $this->search($params['field_1']);
            $model = $model->selectRaw($select)->orderBy('search', 'desc');
        }
        if (isset($params['field_2']) && $params['field_2']) {
            $model = $model->where('field_2', 'like', '%'.$params['field_2'].'%');
        }
        if (isset($params['field_3']) && $params['field_3']) {
            $model = $model->where('field_3', 'like', '%'.$params['field_3'].'%');
        }
        if (isset($params['field_4']) && $params['field_4']) {
            $model = $model->where('field_4', 'like', '%'.$params['field_4'].'%');
        }
        if (isset($params['field_5']) && $params['field_5']) {
            $model = $model->where('field_5', 'like', '%'.$params['field_5'].'%');
        }
        if (isset($params['field_6']) && $params['field_6']) {
            $model = $model->where('field_6', 'like', '%'.$params['field_6'].'%');
        }
        if (isset($params['field_7']) && $params['field_7']) {
            $model = $model->where('field_7', 'like', '%'.$params['field_7'].'%');
        }
        if (isset($params['field_8']) && $params['field_8']) {
            $model = $model->where('field_8', 'like', '%'.$params['field_8'].'%');
        }
        if (isset($params['field_9']) && $params['field_9']) {
            $model = $model->where('field_9', 'like', '%'.$params['field_9'].'%');
        }
        if (isset($params['field_10']) && $params['field_10']) {
            $model = $model->where('field_10', 'like', '%'.$params['field_10'].'%');
        }
        if (isset($params['qtags']) && is_array($params['qtags'])) {
            $tagIds = explode(',', $params['qtags']);
            if (count($tagIds) > 0) {
                $model = $model->whereHas('qtags', function ($query) use ($tagIds) {
                    $query->whereIn('qtag_id', $tagIds);
                });
            }
        }
        $lists = $model->orderBy('id', 'desc')->paginate(isset($params['per_page']) ? (int)$params['per_page'] : 15);
        return $lists;
    }

    private function search($string) {
        ini_set('memory_limit', '512M');
        Jieba::init();
        Finalseg::init();
        $word = Tools::break_string($string, 1, 'array'); // 分成单个字
        $aword = Jieba::cut($string);
        $case = '';
        foreach ($word as $k => $wd) {
            // 全部被打散的单个字 
            if ($wd == '.' || $wd == ' ' || $wd == '。' || $wd == '，' || $wd == '；' || $wd == ',' || $wd == '?' || $wd == '？' || $wd == '：' || $wd == ':' || $wd == '+' || $wd == '-' || $wd == '/' || $wd == '\\') { } else {
                $case .= "CASE WHEN field_1 LIKE '%$wd%' THEN 1 ELSE 0 END + ";
            }
        }
        foreach ($aword as $k => $wd) {
            // 分词 
            $case .= "CASE WHEN field_1 LIKE '%$wd%' THEN 2 ELSE 0 END + ";
        }
        $case .= "0 as search , id, field_1, field_2, field_3, field_4, field_5, field_6, field_7, field_8, field_9, field_10";
        // 使用phpanalysis进行分词
        return $case;
    }

    /**
     * 验证参数
     * @param array $params
     * @param bool $isUpdate
     * @return array
     * @throws \Exception
     */
    private function checkParams(array $params, $isUpdate = false){
        $rules = [
            'field_1' => ['bail', 'nullable', 'string', 'between:1,200'],
            'field_2' => ['bail', 'nullable', 'string', 'between:1,200']
        ];
        if ($isUpdate){
            // 删除必选条件
            foreach ($rules as $field => &$rule){
                if (isset($rule[1]) && $rule[1] == 'required') {
                    unset($rule[1]);
                }
            }
        }
        $validator = Validator::make($params, $rules, [], [
            'field_1' => '名称',
            'field_2' => '路径'
        ]);
        if ($validator->fails()) {
            throw new \Exception($validator->errors()->first(), Code::PARAMETER_ERROR);
        }
        return $params;
    }
}
